<template>
  <view class="confirm-order-page">
    <!-- {{type}} -->
    <!-- 0-时租， 1-酒店， 2-名宿 -->
    <view v-if="type === 1" class="m1 pd30 white over">
      <!-- {{dateRange}} -->
      <view class="t1 c1 f30 mt24">{{startTime}} 入住 - {{endTime}} 离开</view>
      <view class="t1 c1 f30 mt24">{{renderLabel}}</view>
      <view class="tag c2 f24">订单确认后30分钟内免费取消</view>
    </view>
    <view v-else class="m1 pd30 white over">
      <view class="t1 c1 f30 mt24">{{room.times}}</view>
      <view class="t1 c1 f26 mt24">{{room.label}}</view>
      <view class="t1 c1 f24 mt24">{{room.title}}</view>
      <view class="t1 c1 f24 mt24">{{room.remark}}</view>
      <!-- <view class="tag c2 f24">订单确认后30分钟内免费取消</view> -->
    </view>
  
    <view v-if="type === 1 || type === 2" class="m2 c1 m3">
      <view class="cell fr-cs">
        <view class="label bold f30">订房信息</view>
        <view class="operate-box fr-c">
          <view class="reduce" @click="reduce"></view>
          <view class="value">{{payload.roomNumber}}间</view>
          <view class="add" @click="add"></view>
        </view>
      </view>
      <view class="form fr-cs">
        <view class="label f30 c1">住客姓名</view>
        <view class="value f30 flex c1 fr-cs">
          <input v-model="payload.userName" type="text" placeholder="请输入住客姓名">
        </view>
        <image class="icon" src="/hotel/static/icon/user-icon.png"></image>
      </view>
      <view class="form fr-cs">
        <view class="label f30 c1 fr-cf">
          <text>+86</text>
          <image class="img" src="/static/icon/arrow.png"></image>
        </view>
        <view class="value f30 flex c1 fr-cs">
          <input v-model="payload.mobile" type="number" placeholder="请输入手机号">
        </view>
        <image class="icon" src="/hotel/static/icon/contact-icon.png"></image>
      </view>
      <view class="form fr-cs">
        <view class="label f30 c1">入住时段</view>
        <view class="value f30 flex c1 fr-cs" @click="openCancard">
          <input v-if="type === 0" :value="room.check_in_time + ' - ' + room.check_out_time" type="text" disabled placeholder="请选择入住时段">
          <input v-else :value="payload.startTime + ' - ' + payload.endTime" type="text" disabled placeholder="请选择入住时段">
        </view>
      </view>
    </view>
    
    <!-- 0--时宿 -->
    <view v-else class="m2 c1 m3">
      <view class="cell fr-cs">
        <view class="label bold f30">入住信息</view>
      </view>
      <picker mode="selector" :range="priceRange" range-key="label" @change="updateTimeId">
        <view class="form fr-cs">
          <view class="label f30 c1">入住时段</view>
          <view class="value f30 flex c1 fr-cs">
            {{timeStr}}
          </view>
          <image class="icon" src="/static/icon/arrow-icon.png"></image>
        </view>
      </picker>
      <view v-if="type != 0" class="form fr-cs">
        <view class="label f30 c1">房间数量</view>
        <view class="value f30 flex c1 fr-cs">
          <input v-model="room.number" disabled type="text" placeholder="请输入房间数量">
        </view>
      </view>
      <view class="form fr-cs">
        <view class="label f30 c1">住客姓名</view>
        <view class="value f30 flex c1 fr-cs">
          <input v-model="payload.username" type="text" placeholder="请输入住客姓名">
        </view>
      </view>
      <view class="form fr-cs">
        <view class="label f30 c1 fr-cf">
          <text>+86</text>
          <image class="img" src="/static/icon/arrow.png"></image>
        </view>
        <view class="value f30 flex c1 fr-cs">
          <input v-model="payload.mobile" type="number" placeholder="请输入手机号">
        </view>
      </view>
    </view>
    
    <view class="m2 m4">
      <view class="cell fr-cs">
        <view class="label bold f30">本单可享</view>
        <view class="value c3 f30"></view>
      </view>
      <view v-if="type != 0" class="cell fr-cs">
        <view class="label f30">促销优惠</view>
        <view v-if="couponList.length === 0" class="value c3 f30">暂无可用优惠券</view>
        <view class="u-flex" v-else @click="couponShowFun">
          <view v-if="couponIdx > -1" class="value c3 f30">减￥{{couponList[couponIdx].coupon.discount_price}}</view>
          <view class="u-tips-color" v-else>有可用的优惠券</view>
          <image class="icon" src="/static/icon/arrow-icon.png"></image>
        </view>
      </view>
      <view class="cell fr-cs">
        <view class="label f30">离店增积分</view>
        <view class="value f30">{{Math.trunc(totalMoney) || '0'}}积分</view>
        <!-- <image class="icon" src="/static/icon/arrow-icon.png"></image> -->
      </view>
    </view>
    
    <template v-if="type === 1">
      <view class="m2 m5">
        <view class="bt">安心服务</view>
        <view class="bt">发票</view>
        <view class="content">发票由溪棠酒店或其分公司开具，支持专用和普通发票，订单确认后可在订单页开具。</view>
      </view>
      
      <view class="m6">
        <view class="bt">扣款说明：</view>
        <view class="content">订单确认后30分钟内免费取消。逾期不可取消，若未入住将收取您首晚费用￥345 (如用优惠券则以券后支付价为准)。订单需等酒店或供应商确认后生效，订单确认结果以溪棠酒店短信、邮件或app通知为准，如订单不确认将全额退款至您的付款账户</view>
      </view>
      <view class="m6">
        <view class="bt">服务提供商：</view>
        <view class="content">住宿预订服务由携程旗下上海赫程国际旅行社有限公司及其分公司提供，涉及住宿 (含演出票务)套餐的预订服务由上海携程国际旅行社有限公司提供，住宿服务由酒店提供。</view>
      </view>
      
      <view class="m7">请您在提交订单前仔细阅读 <text class="link">溪棠预订条款</text>和<text class="link">个人信息授权声明</text></view>
    </template>
    
    <view v-else class="pay-m1">
      <view class="bt">请选择支付方式</view>
      <view class="pay-item">
        <image class="pay-icon" src="/hotel/static/icon/wechat-icon.png"></image>
        <view class="flex f30">微信支付</view>
        <image class="check" src="/hotel/static/icon/check-icon.png"></image>
      </view>
      <!-- <view class="pay-item">
        <image class="pay-icon" src="/hotel/static/icon/bank-icon.png"></image>
        <view class="flex f30">银行卡支付</view>
        <image class="check" src="/static/icon/check-icon.png"></image>
      </view> -->
    </view>
    
    <view class="bottom-fixed-btn fr-cs">
      <view class="left fr-cf">
        <view class="t1">在线付</view>
        <view class="t2">￥{{totalMoney}}</view>
      </view>
      <view class="right fr-ce">
        <!-- <view class="t3">费用明细</view> -->
        <view class="t4" @click="payment">去支付</view>
      </view>
    </view>
    
    <!-- 优惠券 -->
    <u-popup v-model="couponShow" mode="bottom" border-radius="14">
      <div class="pup">
        <view class="title">
          选择优惠券
          <u-icon name="close" color="#aaa" size="26" @click="show = false"></u-icon>
        </view>
        <view class="coupon-list">
        	<view class="item u-flex u-col-center" v-for="(item, index) in couponList" :key="index" @click="couponSelect(index, item.id)">
            <view class="icon" :class="{on : payload.couponId  == item.id}" :style="{ borderColor: payload.couponId  == item.id ? theme.bgColor : '' }"></view>
            <view v-if="item.coupon">
              <!-- <view class="name u-line-1">{{ item.coupon.condition_text }}</view> -->
              <view class="u-flex">
              	订单满 
                <template>
                  <text class="priorityn" :style="{ color: theme.bgColor }">{{item.coupon.total_price }}元</text>
                  <text>{{ item.coupon.condition == 1 ? '减' : '打' }}</text>
                  <text class="priorityn" :style="{ color: theme.bgColor }">
                  	{{ item.coupon.condition == 1 ? item.coupon.discount_price :item.coupon.discount }}
                  </text>
                  <text>{{ item.coupon.condition == 1 ? '元' : '折' }}</text>
                </template>
              </view>
            </view>
        	</view>
          <!-- <u-button type="primary" class="call-btn u-font-30" @click="pupSubmit">提交</u-button> -->
        </view>
       
        <zb-ipx />
      </div>
    </u-popup>
    <!-- 日历 -->
    <zb-calendar type="range" ref="calendar" :disabledDate="disabledDate" v-model="dateRange" @input="updateDate"></zb-calendar>
  </view>
</template>

<script>
  const app = getApp();
  import moment from 'moment/moment';
  
  export default {
    data() {
      return {
        type: 1, // type  1-酒店，2--名宿， 0-时租房
        payload: {},
        room: {},
        couponList: [],
        priceRange: [],
        disabledDate(item) {
          const val = new Date(item).getTime();
          const cur = Date.now() - 24 * 60 * 60 * 1000;
          if (val < cur) {
            return true
          }
          return false;
        },
        dateRange:[], // 日期
        ms_price:'', // 民宿的价格
        totalMoney:'',
        abc:'',
        couponShow:false,
        couponData:{}, // 优惠券
        priceData:{}, // 价格
        couponIdx: -1
      };
    },
    methods: {
      couponSelect(index, id){
        this.payload.couponId =id;
        this.payload.couponId =id;
        this.couponIdx = index;
        this.couponShow = false;
        this.getPrice(0)
      },
      // 弹出优惠券弹窗
      couponShowFun(){
        this.couponShow = true;
      },
      getPrice (useCoupon = 1){
        // type  1-酒店，2--名宿， 0-时租房
        console.log('datas========', this.priceData)
        let data = {}
        if(useCoupon === 0){
          data = {...this.priceData, coupon_id: this.payload.couponId}
        }else{
          data = {...this.priceData}
        }
        const apiFun = this.type == 1 ? this.$api.getHotelPriceByTimeApi : this.$api.getPriceByTimeApi
        apiFun(data).then(res=>{
          if(res.code != 1) return
          this.totalMoney = res.data.price
          if(this.type != 0 && useCoupon == 1){
            this.couponData.price = this.totalMoney;
            this.getUseCoupon()
          }
        })
        
        
      },
      getUseCoupon(){
        this.$api.useCouponApi(this.couponData).then(res => {
          this.couponList = res.data?.use || []
          // if(this.couponList && this.couponList.length > 0){
          //   this.payload.couponId = this.couponList[0].id
          // }
        })
      },
      // 打开日历
      openCancard() {
        this.$refs.calendar.open()
      },
      
      // 更新日期  type  1-酒店，2--名宿， 0-时租房
      updateDate() {
        if(this.type == 2){
          this.payload.startTime = this.dateRange[0]
          this.payload.endTime = this.dateRange[1];
          getPrice()
        }else if(this.type == 1){
          this.room.check_in_time = this.dateRange[0]
          this.room.check_out_time = this.dateRange[1]
        }
      },
      updateTimeId(e) {
        const v = this.priceRange[e.detail.value]
        this.payload.time_list_id = v.id
        this.getPrice(this.priceRange[e.detail.value])
      },
      // 减少
      reduce() {
        if (this.payload.roomNumber > 1) {
          this.payload.roomNumber -= 1;
          this.priceData.room_number = this.payload.roomNumber;
          this.getPrice()
        }
      },
      // 增加
      add() {
        this.payload.roomNumber += 1;
        this.priceData.room_number = this.payload.roomNumber;
        this.getPrice()
      },
      myShowToast(msg){
        uni.showToast({
          icon: 'none',
          title: msg
        })
      },
      goPay(res){
        if(res.code === 1){
          uni.requestPayment({
          	provider: 'wxpay',
          	timeStamp: res.data.timeStamp,
          	nonceStr: res.data.nonceStr,
          	package: res.data.package,
          	signType: res.data.signType,
          	paySign: res.data.paySign,
          	success: rest => {
          		this.$u.toast('支付成功！');
             setTimeout(()=>{
               this.$u.route('/hotel/order/order');
             })
          	},
          	fail: err => {
          		if (err.errMsg == "requestPayment:fail cancel") {
          		  this.$u.toast('支付已取消');
          		}else{
          		  this.$u.toast('错误：' + err.errMsg)
          		}
          	}
          });
        }else{
          this.$u.toast(res.msg);
        }
        
        uni.hideLoading()
      },
       // 支付  type  1-酒店，2--名宿， 0-时租房
       payment() {
         if (this.type === 1) {
           if (this.payload.userName === '') return this.myShowToast('请输入住户姓名')
           if (this.payload.mobile === '') return this.myShowToast('请输入手机号')
           uni.setStorageSync('payload', this.payload)
           uni.navigateTo({
             url: 'payment?type='+this.type+'&price='+this.totalMoney
           })
         } else if(this.type == 2){
           if (this.payload.userName === '') return this.myShowToast('请输入住客姓名')
           if (this.payload.mobile === '') return this.myShowToast('请输入手机号')
           uni.setStorageSync('payload', this.payload)
           uni.showLoading({
             mask: true
           })
           this.$api.famousSetOrdersApi({
             start_time: this.payload.startTime,
             end_time: this.payload.endTime,
             hotel_id: this.payload.hotelId,
             room_type: this.payload.roomTypeId,
             user_name: this.payload.userName,
             mobile: this.payload.mobile,
             room_number: this.payload.roomNumber,
             coupon_id: this.payload.couponId,
           }).then(res => {
             this.goPay(res)
             console.log('data === ', res.data)
           }).catch(() => {
             uni.hideLoading()
           })
           
           
           console.log('this.payload', this.payload)
         }else{
           if (this.payload.time_list_id === '') return this.myShowToast('请选择入住时段')
           if (this.payload.userName === '') return this.myShowToast('请输入住客姓名')
           if (this.payload.mobile === '') return this.myShowToast('请输入手机号')
           uni.showLoading({
             mask: true
           })
           this.$api.timeSetOrdersApi(this.payload).then(res => {
             this.goPay(res)
             console.log('data === ', res.data)
           }).catch(() => {
             uni.hideLoading()
           })
         }
       }
    },
    computed: {
      timeStr() {
        if (this.payload.time_list_id) {
          return this.priceRange.find(v => v.id == this.payload.time_list_id).label
        }
        return '请选择'
      },
      renderLabel() {
        if (this.room.label && Array.isArray(this.room.label)) {
          return (this.room?.label || []).join(' | ')
        }
        return '-'
      },
      startTime() {
        return moment(this.payload.startTime).format('MM月DD日')
      },
      endTime() {
        return moment(this.payload.endTime).format('MM月DD日')
      }
    },
    onLoad(options) {
      // 1-酒店，2--名宿， 0-时租房
      this.type = Number(options?.type || '1');
      let title = '时租房订单详情'
      if(this.type == 1){
        title = "酒店订单详情"
      }else if(this.type == 2){
        title = "民宿订单详情"
      }
      uni.setNavigationBarTitle({
        title:title
      })
      // type  1-酒店，2--名宿， 0-时租房
      if (this.type === 1) {
        const { hotelPayload, roomInfo, payload } = app.globalData
        console.log('payload---', hotelPayload, roomInfo)
        this.room = { ...roomInfo }
        this.payload = {
          startTime: hotelPayload.start,
          endTime: hotelPayload.end_time,
          hotelId: roomInfo.hotel_id,
          roomTypeId: roomInfo.id,
          userName: '',
          mobile: '',
          roomNumber: 1,
          couponId: '',
        }
        this.dateRange = [hotelPayload.start, hotelPayload.end_time]
        this.couponData = {
          price: roomInfo.price,
          hotelId: roomInfo.hotel_id
        }
        this.priceData = {
          hotel_id:this.payload.hotelId,
          start_time: this.payload.startTime,
          end_time:this.payload.endTime,
          room_type_id:this.payload.roomTypeId,
          room_number:this.payload.roomNumber || 1,
        }
        
      } else if (this.type === 2) {
        const famousInfo = uni.getStorageSync('famousInfo')
        // this.room = { ...roomInfo }
        this.payload = {
          startTime: options.start,
          endTime: options.end_time,
          hotelId: famousInfo.id,
          roomTypeId: options.room_type,
          userName: '',
          mobile: '',
          roomNumber: 1, // 房间数量
          couponId: '',
          price:options.price
        }
        this.dateRange = [options.start, options.end_time]
        this.couponData = {
          price: famousInfo.price,
          hotelId: famousInfo.hotel_id
        }
        this.priceData = {
          hotel_id:this.payload.hotelId,
          start_time: this.payload.startTime,
          end_time:this.payload.endTime,
          room_type_id:this.payload.roomTypeId,
          room_number:this.payload.roomNumber || 1,
        }
      } else {
        const timeInfo = uni.getStorageSync('timeInfo')
        this.payload = {
          hotel_id: options.hotelId,
          rental_price_id: options.rentalPriceId,
          username: '',
          mobile: '',
          time_list_id: ''
        }
        this.$api.placeOrderApi(options).then(res => {
          this.room = res.data
          this.payload.price = res.data.price
        })
        this.$api.timeListApi(options).then(res => {
          this.priceRange = res.data.map(v => {
            v.label = v.start_time + ' - ' + v.end_time
            return v
          })
        })
        this.priceData = {
          hotel_id:timeInfo.hotelId,
          start_time: timeInfo.start,
          end_time:timeInfo.end_time,
          room_type_id:timeInfo.room_type_id,
          room_number:this.payload.room_number || 1,
        }
      }
      
      console.log('this.priceData----', this.priceData)
      this.getPrice()
    }
  }
</script>

<style lang="scss" scoped>
.pup{
  
  .title{font-size: 32rpx; display: flex; align-items: center; justify-content: space-between; padding: 20rpx; border-bottom: 1px solid #ededed; margin-bottom: 20rpx;}
}
.coupon-list {
  padding:0 20rpx 30rpx;
	.item {
		background-color: #ffffff;
		margin-bottom: 30rpx;
		border-radius: 10rpx;
    padding: 20rpx 0;
    .name{font-size: 30rpx; margin-bottom: 10rpx;}
    .icon{
      width: 30rpx; height: 30rpx; border-radius: 50%; border: 1px solid #ddd; box-sizing: border-box; margin-right: 20rpx;
      &.on{
        border-width: 8rpx;
      }
    }
	}
}
  
  
.mt24 {
  margin-top: 24rpx;
  margin-bottom: 24rpx;
}
.pd30 {
  padding-left: 30rpx;
  padding-right: 30rpx;
}
.c1 {
  color: #3C3D3E;
}
.c2 {
  color: #2A70F9;
}
.f30 {
  font-size: 30rpx;
}
.f24 {
  font-size: 24rpx;
}
.confirm-order-page {
  overflow: hidden;
  padding-bottom: calc(86rpx + env(safe-area-inset-bottom));
  .m1 {
    padding-bottom: 28rpx;
    .tag {
      display: inline-block;
      line-height: 48rpx;
      padding: 0 12rpx;
      border-radius: 8rpx;
      border: 2rpx solid rgba(#2A70F9,.53);
    }
  }
  .pay-m1 {
    background-color: #fff;
    margin: 30rpx;
    box-sizing: border-box;
    padding: 0 30rpx;
    overflow: hidden;
    border-radius: 16rpx;
    .cell {
      margin: 20rpx 0;
    }
    .bt {
      line-height: 90rpx;
      font-size: 30rpx;
      color: #3C3D3E;
      font-weight: bold;
    }
    .form {
      @include flex(row,flex-start,center);
      box-shadow: 0 1px 0 #eee;
      .label {
        line-height: 98rpx;
        width: 210rpx;
      }
      .value {
        line-height: 98rpx;
        flex: 1;
        .top {
          .icon {
            width: 32rpx;
            height: 32rpx;
          }
        }
        .bottom {
          line-height: 1.5;
          padding-bottom: 30rpx;
        }
      }
    }
    .pay-item {
      height: 100rpx;
      @include flex;
      box-shadow: 0 -1px 0 #eee;
      .pay-icon {
        width: 34rpx;
        height: 34rpx;
        margin-right: 10rpx;
      }
      .check {
        width: 28rpx;
        height: 30rpx;
      }
    }
  }
  .m2 {
    margin: 30rpx;
    border-radius: 16rpx;
    background-color: #fff;
    overflow: hidden;
    font-size: 30rpx;
    padding: 0 30rpx;
  }
  .m3 {
    .cell {
      line-height: 98rpx;
      font-size: 30rpx;
      .reduce {
        width: 38rpx;
        height: 38rpx;
        border-radius: 50%;
        border: 2rpx solid #ddd;
        line-height: 34rpx;
        text-align: center;
        box-sizing: border-box;
        position: relative;
        &::after {
          content: '';
          width: 50%;
          height: 2px;
          background-color: #3C3D3E;
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%,-50%);
        }
      }
      .value {
        width: 80rpx;
        text-align: center;
        font-size: 34rpx;
        color: #151515;
      }
      .add {
        box-sizing: border-box;
        width: 38rpx;
        height: 38rpx;
        border-radius: 50%;
        border: 2rpx solid #2A70F9;
        background-color: #2A70F9;
        line-height: 34rpx;
        text-align: center;
        position: relative;
        &::before {
          content: '';
          height: 50%;
          width: 2px;
          background-color: #fff;
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%,-50%);
        }
        &::after {
          content: '';
          width: 50%;
          height: 2px;
          background-color: #fff;
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%,-50%);
        }
      }
    }
    .form {
      line-height: 98rpx;
      box-shadow: 0 1px 0 #eee;
      .label {
        width: 156rpx;
        .img {
          width: 34rpx;
          height: 36rpx;
          margin-left: 12rpx;
        }
      }
      input {
        height: 98rpx;
        font-size: 30rpx;
        display: block;
        width: 100%;
      }
      .icon {
        width: 40rpx;
        height: 40rpx;
      }
    }
  }
  .m4 {
    line-height: 78rpx;
    padding-top: 12rpx;
    padding-bottom: 12rpx;
    .label {
      flex: 1;
    }
    .c3 {
      color: #E97407;
      font-weight: bold;
    }
    .icon {
      width: 40rpx;
      height: 40rpx;
    }
  }
  .m5 {
    .bt {
      font-size: 30rpx;
      font-weight: bold;
      margin: 30rpx 0;
    }
    .content {
      font-size: 24rpx;
      line-height: 34rpx;
      color: #3C3D3E;
      margin-bottom: 42rpx;
    }
  }
  .m6 {
    overflow: hidden;
    margin: 0 30rpx;
    .bt {
      font-size: 30rpx;
      color: #3C3D3E;
      font-weight: bold;
      margin: 22rpx 0;
    }
    .content {
      font-size: 24rpx;
      text-align: justify;
      line-height: 1.8;
      margin-bottom: 60rpx;
    }
  }
  .m7 {
    margin: 0 30rpx;
    font-size: 24rpx;
    color: #333;
    padding-bottom: 30rpx;
    .link {
      color: #2A70F9;
    }
  }
}

.bottom-fixed-btn {
  background-color: #fff;
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 9;
  box-shadow: 0rpx 0rpx 12rpx 0rpx rgba(0,0,0,0.07);
  width: 100%;
  box-sizing: border-box;
  padding: 0 30rpx env(safe-area-inset-bottom);
  height: calc(126rpx + env(safe-area-inset-bottom));
  .left {
    .t1 {
      color: #333333;
      font-size: 30rpx;
      font-weight: bold;
      margin-right: 10rpx;
    }
    .t2 {
      font-size: 30rpx;
      color: #2A70F9;
      font-weight: bold;
    }
  }
  .right {
    .t3 {
      font-size: 24rpx;
      color: #2A70F9;
    }
    .t4 {
      margin-left: 10rpx;
      background-color: #2A70F9;
      width: 94rpx;
      height: 42rpx;
      line-height: 42rpx;
      text-align: center;
      background: #2A70F9;
      border-radius: 4rpx;
      font-size: 24rpx;
      color: #FFFFFF;
    }
  }
}
</style>
